package bb.lanxing.fragment.discover;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.adapter.discover.BbsListAdapter;
import bb.lanxing.fragment.base.BaseFragment;
import bb.lanxing.model.database.Bbs;
import bb.lanxing.model.database.User;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import okhttp3.Request;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class BbsListFragment extends BaseFragment {
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView bbsRecyclerView;
    private BbsListAdapter mBbsListAdapter = new BbsListAdapter();
    private List<Bbs> bbsList = new ArrayList<>();
    private int userId = 0;

    private int type = 0;

    private int pageMax = 1;
    private int page = 1;

    public BbsListFragment() {
        super(R.layout.fragment_team_list);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_team_list, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mSwipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        mSwipeRefreshLayout.setOnRefreshListener(() -> loadData(true));
        bbsRecyclerView = view.findViewById(R.id.recyclerView);
        bbsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBbsListAdapter.setOnItemClickListener(position -> {
            if (0 == bbsList.get(position).myLike) {
                bbsList.get(position).myLike = 1;
                bbsList.get(position).likesCount += 1;
            } else {
                bbsList.get(position).myLike = 0;
                bbsList.get(position).likesCount -= 1;
            }
            if (bbsList.get(position).likesCount < 0) {
                bbsList.get(position).likesCount = 0;
            }
            mBbsListAdapter.notifyDataSetChanged();
            postlike(bbsList.get(position).serverId, bbsList.get(position).myLike);
        });
        bbsRecyclerView.setAdapter(mBbsListAdapter);
        bbsRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1)) {
                    loadData(false);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

        User signinUser = App.getContext().getSigninUser();
        if (signinUser != null) {
            userId = signinUser.getUid();
        }
        loadData(true);
    }

    private void loadData(final boolean bPullDown) {
        if (bPullDown) {
            page = 1;
        } else {
            page++;
            if (page > pageMax) {
                return;
            }
        }
        BiCiCallback biCiCallback = new BiCiCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
                if (mSwipeRefreshLayout != null) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }

            @Override
            public void onResponseString(@NonNull String string) {
                if (mSwipeRefreshLayout != null) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
                if (!TextUtils.isEmpty(string)) {
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        int code = jsonObject.optInt("code");
                        if (200 == code) {
                            int totalListNumber = jsonObject.optInt("total");
                            pageMax = totalListNumber / 10;
                            if (totalListNumber % 10 > 0) {
                                pageMax++;
                            }
                            ArrayList<Bbs> arrayList = new ArrayList<>();
                            try {
                                JSONArray jSONArray = new JSONObject(string).getJSONArray("rows");
                                for (int i = 0; i < jSONArray.length(); i++) {
                                    Bbs createByJson = Bbs.createByJson(jSONArray.getJSONObject(i));
                                    arrayList.add(createByJson);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            updateDatas(arrayList, bPullDown);
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    toast("获取帖子数据失败");
                }
            }
        };
        MyHttpClient.requestBbsList(biCiCallback, page, 10, type, userId);
    }

    private synchronized void updateDatas(final List<Bbs> arrayList, final boolean needClean) {
        if (arrayList == null) {
            return;
        }
        if (mBbsListAdapter != null) {
            if (needClean) {
                bbsList.clear();
            }
            bbsList.addAll(arrayList);
            mBbsListAdapter.updateData(bbsList);
        }
    }

    private void postlike(int bbsId, int isLike) {
        Observable.create(new NetSubscribe(MyHttpClient.commitBbslike(bbsId, isLike))).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable th) {
                        toast("点赞失败");
                    }

                    @Override
                    public void onNext(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JSONObject jsonObject = new JSONObject(str);
                                int code = jsonObject.optInt("code");
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            toast("点赞失败");
                        }
                    }
                });
    }

    public void setType(int type) {
        this.type = type;
    }
}